<template>
<div>
  <el-popover
    ref="popover4"
    placement="bottom-end"
    class="popover"
    width="366"
    trigger="click"
    >
    <el-tabs v-model="activeName" @tab-click="handleClick" class="tabs" type="card" >
      <el-tab-pane name="notice" >
        <span slot="label" >通知 {{ unhandled_message_num }}</span>
        <div>
          <div class="content">
            <div v-if="msgData && msgData.length >0" >
              <div class="item" v-for="(item, index) in msgData" :key="index" @click="handleViewMsg(item)">
                <div class="item_left" > 
                  <div class="avatar"><img class="avatar-image" :src="item.creator.user_avatar_url"></div>
                </div>
                <div class="item_content" > 
                    <div class="item_title">
                      {{item.creator.username}} {{item.content}}
                    </div>
                  <div class="item_description">
                    <div v-if="item.remark">{{item.remark}}</div>
                    <div v-if="item.create_date" > {{ item.create_date | timeFromNowFilter }}</div>
                  </div>
                </div>
              </div>
            </div>
            <div class="content-blank" v-else >
              暂没有新消息
            </div>
          </div>
          <div class="tail"> 
            <div><el-button type="text" @click="markReadInfos()" >当前所有标记为已读</el-button></div>
            <div><el-button type="text" @click="showNotifications()" >查看全部</el-button></div>
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane name="todo">
        <span slot="label" style="width:120px" >待办 {{unhandled_todo_num}}</span>
        <div>
          <div class="content">
            <div v-if="todoData && todoData.length >0" >
              <div class="item" v-for="(item, index) in todoData" :key="index" @click="handleViewTodo(item)">
                <div class="item_left" > 
                  <div class="avatar"><img class="avatar-image" :src="item.creator.user_avatar_url"></div>
                </div>
                <div class="item_content" > 
                    <div class="item_title">
                      {{item.creator.username}} {{item.content}}
                    </div>
                  <div class="item_description">
                    <div v-if="item.remark">{{item.remark}}</div>
                    <div v-if="item.create_date" > {{ item.create_date | timeFromNowFilter }}</div>
                  </div>
                </div>
              </div>
            </div>
            <div v-else class="content-blank" >
              暂没有新待办
            </div>
          </div>

          <div class="tail" style="justify-content: flex-end;"> 
            <div><el-button type="text" @click="showTodo()" >查看全部 </el-button></div>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
  </el-popover>
  <div class='noticeButton' v-popover:popover4 >
    <el-badge :value="unhandled_notifications_num" class="item ">
    <svg-icon class-name='message-icon' icon-class="bell" />
    </el-badge>
  </div>
</div>

</template>

<script>
import API from '@/utils/backend_api'
import { mapGetters } from 'vuex'
export default {
  data() {
    return {
      msg_num: 0,
      offset: 0,
      limit: 5,
      isStretch: true,
      activeName: 'notice',
      unhandled_message_num: 0,
      unhandled_todo_num: 0,
      msgData: [],
      todoData: []
    }
  },
  created() {
    this.$connect()
    console.log('socket connect:', this.$socket)
    this.refreshMessage()
    this.refreshTodo()
  },
  computed: {
    ...mapGetters([
      'socket'
    ]),
    unhandled_notifications_num: function() {
      return Number(this.unhandled_message_num) + Number(this.unhandled_todo_num)
    }
  },
  watch: {
    socket: {
      handler(val, oldVal) {
        if (val.message && val.message !== '') {
          const msgObj = JSON.parse(val.message)
          console.log('notify msgObj=', msgObj)
          /* 处理通知，刷新消息通知 */
          if (msgObj.type && msgObj.type !== 'keepAlive' && msgObj.type !== 'upload') {
            this.refreshMessage()
            this.refreshTodo()
            this.$notify.info({
              title: '消息',
              message: msgObj.content,
              position: 'bottom-right'
            })
          }
        }
      },
      deep: true
    }
  },
  methods: {
    markReadInfos() {
      const msg_group = []
      this.msgData.map(msg => {
        msg_group.push(msg.id)
      })
      API.notification.read_messages({
        msg_group: msg_group
      }).then(response => {
        this.refreshMessage()
      })
    },
    handleViewMsg(data) {
      const msg_group = []
      if (data && data.id && data.url) {
        msg_group.push(data.id)
      }
      API.notification.read_messages({
        msg_group: msg_group
      }).then(response => {
        this.$router.push({ path: data.url })
        this.refreshMessage()
      })
    },
    handleViewTodo(data) {
      API.todo.is_handle(data.id).then(response => {
        if (response.data && response.data.is_handle && response.data.is_handle === '1') {
          this.$message('该待办已被处理')
          this.refreshTodo()
        } else {
          if (data.url) {
            this.$router.push({ path: data.url })
          }
        }
      })
    },
    refreshMessage() {
      API.notification.message({
        is_handle: '0',
        offset: this.offset,
        limit: this.limit,
        sort: '-create_date'
      }).then(response => {
        this.unhandled_message_num = Number(response.headers['x-total-count'])
        if (response.data) {
          this.msgData = response.data
        } else {
          this.msgData = []
        }
      })
    },
    refreshTodo() {

      API.notification.todo({
        is_handle: '0',
        offset: this.offset,
        limit: this.limit,
        sort: '-create_date'
      }).then(response => {
        const h = this.$createElement;
        this.unhandled_todo_num = Number(response.headers['x-total-count'])
        if (response.data) {
          this.todoData = response.data
        } else {
          this.todoData = []
        }
        if (this.unhandled_todo_num >0) {
          this.$notify.info({
            title: '提醒',
            message:  h('i', { style: 'color: teal'},  '您有' + this.unhandled_todo_num + '个待办需要处理！'),
            position: 'top-right'
          })
        }

      })
    },
    handleClick(tab, event) {
      console.log(tab, event)
    },
    showNotifications() {
      this.$router.push({
        name: 'notifications',
        params: {
        }
      })
    },
    showTodo() {
      this.$router.push({
        name: 'todo',
        params: {
        }
      })
    }
  },
  beforeDestroy() {
    console.log('socket disconnect:', this.$socket)
    this.$disconnect()
  }
}
</script>

<style scoped>
.noticeButton {
  cursor: pointer;
  display: inline-block;
  transition: all .3s;
}
.icon {
  font-size: 16px;
  padding: 4px;
}
.message-icon {
  font-size: 20px;
  cursor: pointer;
  vertical-align: 8px!important;
}
.item {
  margin-top: 0px;
  margin-right: 10px;
}
.tail{
  display: flex;
  justify-content: space-between;
}
.line{
  height: 1px;
  border-top: 1px solid #ddd;
  text-align: center;
}
/* .content {
} */
.content-blank{
  text-align: center;
  padding-bottom: 12px;
  border-bottom: 1px solid #e8e8e8;
}
.item {
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  justify-content: space-between;
  align-items: flex-start;
  align-content: flex-start;
  border-bottom: 1px solid #e8e8e8;
  cursor: pointer;
  padding-top: 2px;
  padding-bottom: 4px;
}
.item:hover{
  background-color: #e6f7ff;
}
.item_left{
  display: flex;
}

.avatar{
  flex: 0 0 0px;
  margin-left: 2px;
  margin-top: 2px;
}
.avatar-image {
  width: 30px;
  height: 30px;
  border-radius: 10px
}
.item_title{
  font-size: 14px; 
  line-height: 22px;
  font-weight: 400;
  color: rgba(0,0,0,.65);
  /* margin-bottom: 12px; */
}
.item_content{
  position: relative;
  top: 0px;
  margin-left: 10px;
  flex: 1 1 auto;
  line-height: 22px;
}
.item_description{
  color:rgba(0,0,0,.45);
  font-size: 12px; 
  font-weight: 400;
  line-height: 18px;
}
</style>


